package uk.ac.cam.cl.oscar.Mobile_Client;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.VideoControl;
import javax.microedition.io.*;
import java.io.*;

public class PictureClient extends MIDlet implements Runnable{
    
    List mainMenu;
    javax.microedition.lcdui.Form snapshotScreen;
    javax.microedition.lcdui.Form resultsForm;
    Display display;
    Player player;
    VideoControl videoControl;
    Item videoItem;
    Command snap;
    Command back;
    Command main;
    String serverUrl = "socket://131.111.221.193:8000";
    String[] artist;
    String[] id;
    String[] blurb;
    String[] cost;
    String[] score;
    byte[][] images;
   
    public void startApp() {
        /*get display*/
        display = Display.getDisplay(this);
        /*setup menus*/
        setupMenus();
        /*initially display main menu*/
        display.setCurrent(mainMenu);
    }
    
    public void run(){
        try{
            //setup connections
            StreamConnection sc = (StreamConnection)Connector.open(serverUrl);
            DataOutputStream dos = sc.openDataOutputStream();
            DataInputStream dis = sc.openDataInputStream();
            //take snapshot
            byte[] buffer = videoControl.getSnapshot(null);
            //send snapshot
            dos.write(buffer, 0, buffer.length);
            //read result
            int length = dis.readInt();
            int a = dis.readInt();
            int b = dis.readInt();
            int c = dis.readInt();
            //reset arrays
            artist = new String[length];
            id = new String[length];
            blurb = new String[length];
            cost = new String[length];
            images = new byte[length][];
            score = new String[length];
            //read info
            for(int i = 0; i < length; i++){
                artist[i] = dis.readUTF();
                id[i] = dis.readUTF();
                blurb[i] = dis.readUTF();
                cost[i] = dis.readUTF();
                score[i]=dis.readUTF();
            }

            byte[] imageBuffer = new byte[a+b+c];
            dis.readFully(imageBuffer, 0, a+b+c);
            
            int[] positions = new int[3];
            positions[0]=0;
            positions[1]=a;
            positions[2]=b;
            int sizes[] = new int[3];
            sizes[0] = a;
            sizes[1] = b;
            sizes[2] = c;
            
            //Set heading for results form
            StringItem heading = new StringItem("Results found: ", "");
            heading.setLayout(Item.LAYOUT_2|Item.LAYOUT_CENTER|Item.LAYOUT_NEWLINE_BEFORE|Item.LAYOUT_NEWLINE_AFTER);
            resultsForm.append(heading);
            
            //Add results to results form
            for(int i = 0; i < length; i++){
                byte[] temp = new byte[sizes[i]];
                System.arraycopy(imageBuffer, positions[i], temp, 0, sizes[i]);
                Image image = Image.createImage(temp, 0, temp.length);
                
                images[i] = temp;
                ImageItem imageItem = new ImageItem("", image, Item.LAYOUT_2|Item.LAYOUT_NEWLINE_BEFORE|Item.LAYOUT_NEWLINE_AFTER, "");
                resultsForm.append(imageItem);
                
                String info = new String();
                info = "Poster ID: " + id[i] + "\n" + "Artist: " + artist[i] + "\n" + "Blurb: " +blurb[i] + "\n" + "Cost: " + cost[i] + "\n" + "Match: " + score[i] + "%";
                StringItem stringItem = new StringItem("", info);
                stringItem.setLayout(Item.LAYOUT_2);
                
                resultsForm.append(stringItem);
                
            }            
            

        }
        catch(MediaException e){
            
        }
        catch(IOException e){
            
        }
        display.setCurrent(resultsForm);        
        
    }
    
    
    public void setupMenus(){
        /*Create Commands*/
        snap = new Command("Take picture", Command.SCREEN, 0);
        back = new Command("Back", Command.BACK, 0);
        main = new Command("Main Menu", Command.EXIT, 0);
        /*Setup main menu*/
        mainMenu = new List("Oscar Picture Client v1.0", List.IMPLICIT);
        mainMenu.append("Search", null);
        mainMenu.append("Exit", null);
        mainMenu.setCommandListener(new CommandListener(){
            public void commandAction(Command c, Displayable s){
                if(mainMenu.getSelectedIndex()==0){
                    display.setCurrent(snapshotScreen);
                }
                else if(mainMenu.getSelectedIndex()==1){
                    notifyDestroyed();
                }
            }
        });
        /*setup snapshot screen*/
        snapshotScreen = new Form("Please Take a Picture");
        snapshotScreen.addCommand(back);
        snapshotScreen.addCommand(snap);

        snapshotScreen.setCommandListener(new CommandListener(){
            public void commandAction(Command c, Displayable s){
                if(c.getCommandType()==Command.SCREEN){
                    Form waiting = new Form("Please Wait");
                    Ticker ticker = new Ticker("Downloading");
                    waiting.setTicker(ticker);
                    StringItem message = new StringItem("", "Please wait, it may take a few seconds to retrieve the results");
                    message.setLayout(Item.LAYOUT_2|Item.LAYOUT_CENTER|Item.LAYOUT_VCENTER);
                    waiting.append(message);
                    display.setCurrent(waiting);

                    startNetworkThread();
                }
                else if(c.getCommandType()==Command.BACK){
                    display.setCurrent(mainMenu);
                }
            }
        });
        
        /*Setup snapshot screens camera feed*/
        try{
            player = Manager.createPlayer("capture://video");
            player.realize();
            videoControl = (VideoControl)player.getControl("VideoControl");
            videoItem = (Item)videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null);
            videoItem.setLayout(Item.LAYOUT_2|Item.LAYOUT_EXPAND);
            snapshotScreen.append(videoItem);
            player.start();
        }
        catch(Exception e){
            
        }
        /*Setup Results Form*/
        resultsForm = new Form("Results Found.....");
        resultsForm.addCommand(back);
        resultsForm.addCommand(main);
        resultsForm.setCommandListener(new CommandListener(){
            public void commandAction(Command c, Displayable s){
                if(c.getCommandType()==Command.BACK){
                    resultsForm.deleteAll();
                    display.setCurrent(snapshotScreen);
                }
                else if(c.getCommandType()==Command.EXIT){
                    resultsForm.deleteAll();
                    display.setCurrent(mainMenu);
                }
            }
        });
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
    
    public void startNetworkThread(){ 
        Thread t = new Thread(this);
        t.start();
    }
}
